package gwtappcontainer.server;

import gwtappcontainer.server.apps.content.ContentAPI;
import gwtappcontainer.server.apps.geolocation.GeoLocationAPI;
import gwtappcontainer.shared.apis.APIResponse;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apps.geolocation.LocationProp;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GeoContentServlet extends HttpServlet {
        private Logger logger = Logger.getLogger(ContentAPI.class.getName());
       
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                        throws IOException {
               
            resp.setContentType("text/html");              
           
            final String PARAM_TAG = "tag";
            String tag = req.getParameter(PARAM_TAG);
           
            if (null == tag) {
                    String errMessage = "Query param [" + PARAM_TAG + "] not found in query string";
                    logger.warning(errMessage);
                    resp.getWriter().println(errMessage);
                    return;
            }
           
            GeoLocationAPI api = new GeoLocationAPI();
            APIResponse response = api.getLocation(req);
            if (response.statusCode != Status.SUCCESS) {
                    String errMessage = "Unexpected error - Unable to retreive location " +
                                    "<br><br> Error message from GeoLocationAPI <br> - " +
                                    response.userFriendlyMessage;
                   
                    resp.getWriter().println(errMessage);
                    return;
            }
           
            LocationProp prop = (LocationProp) response.object;            
           
            response = api.getMostRelevantContent(tag, prop.city,
                            prop.region, prop.country);
                           
            if (response.statusCode != Status.SUCCESS) {
                    resp.getWriter().println(response.userFriendlyMessage);
                    return;
            }
           
            String content = response.object.toString();
           
            resp.getWriter().println(content);
            return;                                
        }
}

